package bd403.Backend;

import java.util.InputMismatchException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import bd403.namespace.BDActivity;
import bd403.namespace.R;
import bd403.utils.KeyboardSetup;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

/* UI and functionality for the Registration page of the BrewDawg application.
 * Main author: Mike
 */

public class Registration extends Activity {
	
	private final String URL_START = "http://cubist.cs.washington.edu/~jhl123/index.php?";
	private final String HTTP_USER_SUFFIX = "var1=getusers";
	private final String HTTP_USERADD_SUFFIX = "var1=adduser";
	
	/* Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setContentView(R.layout.registration);
		setupKeyboard();
		
		final EditText userText = (EditText) findViewById(R.id.registeruser);
        final EditText passText = (EditText) findViewById(R.id.registerpassword);
        final EditText verifyText = (EditText) findViewById(R.id.verify);
        final CheckBox cb = (CheckBox) findViewById(R.id.agecheck);
		
        // Initialize listener for the 'Registration' button.
		Button login = (Button) findViewById(R.id.registerButton);
		login.setOnClickListener(new View.OnClickListener() {
	        public void onClick(View view) {
	        	if (hasConnection()) {
		        	try {
			        	if (inputCheck(userText.getText().toString().toLowerCase(), 
			        			passText.getText().toString().toLowerCase(), 
			        			verifyText.getText().toString().toLowerCase())) {
			        		
			        		if (!cb.isChecked()) {
			        			Toast.makeText(getApplicationContext(), getString(R.string.toast_register_age), Toast.LENGTH_SHORT).show();
			        		} else if (register(userText.getText().toString().toLowerCase(), passText.getText().toString().toLowerCase())) {
			        			Toast.makeText(getApplicationContext(), getString(R.string.toast_register_success), Toast.LENGTH_LONG).show();
			        
			        			DrinkStorage ds = (DrinkStorage)getApplicationContext();
			    				ds.initializeUser(userText.getText().toString().toLowerCase());
			    				startActivity(new Intent(getApplicationContext(), BDActivity.class));
			    				finish(); // prevent users from going back to the Registration page
			        			
			        		} else {
			        			Toast.makeText(getApplicationContext(), getString(R.string.toast_register_error), Toast.LENGTH_SHORT).show();
			        		}
			        	}
		        	} catch (InputMismatchException e) {
		        		Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
		        	}
	        	} else {
	        		Toast.makeText(getApplicationContext(), getString(R.string.toast_register_noconn), Toast.LENGTH_SHORT).show();
	        	}
	        };
		});
    }
    
    /* Handler to switch back to the Login page */
    public void clickHandle(View v){    	
    	startActivity(new Intent(getApplicationContext(), Login.class));
    	finish();
    }
    
    /* Initializes keyboard settings for the Registration page.
     */
    private void setupKeyboard() {
    	final EditText userText = (EditText) findViewById(R.id.registeruser);
        final EditText passText = (EditText) findViewById(R.id.registerpassword);
        final EditText verifyText = (EditText) findViewById(R.id.verify);
      	
        KeyboardSetup ks = KeyboardSetup.getInstance(this);
    	// Changes enter key on soft keyboard to minimize keyboard
        ks.setupKeyboard(userText);
        ks.setupKeyboard(passText);
        ks.setupKeyboard(verifyText);
    }
    
    /* Returns true if an Internet connection is available, otherwise returns false. */
	private boolean hasConnection() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null;
    }
    
    /* Accepts a user name as parameter and returns true if this user name is not already
     * taken. Otherwise returns false.
     */
    private boolean containsUser(String user) {
    	String currUsers = DrinkDB.httpConn(URL_START + HTTP_USER_SUFFIX);
    	JSONArray jArr;
		try {
			jArr = new JSONArray(currUsers);
			JSONObject json_data = null;
			for (int i = 0; i < jArr.length(); i++) {
				json_data = jArr.getJSONObject(i);
				if (user.equals(json_data.get("name").toString())) {
					return true;
				}
			}
		} catch (JSONException e) {
			// return true on an error so we don't accidently add duplicate users
			return true;
		}
		return false;
    }
    
    /* Accepts a user name, password, and verified password as parameters and returns true
     * if the input is legal for registration. Otherwise returns false.
     */
    private boolean inputCheck(String user, String pass, String verify) {
    	if (user.equals("") || pass.equals("") || verify.equals("")) {
    		throw new InputMismatchException(getString(R.string.reg_submiterr_blank));
    	} else if (!validChar(user)) {
    		throw new InputMismatchException(getString(R.string.reg_submiterr_name));
    	} else if (!validChar(pass)) {
    		throw new InputMismatchException(getString(R.string.reg_submiterr_pass));
    	} else if (!pass.equals(verify)) {
    		throw new InputMismatchException(getString(R.string.reg_submiterr_passmatch));
    	} else if (containsUser(user)) {
    		throw new InputMismatchException(getString(R.string.reg_submiterr_taken));
    	} else {
    		return true;
    	}
    }
    
    /* Accepts a String username and String password as parameter, and returns true if a
     * successful registration with the username/password occured. Otherwise returns false.
     */
    private boolean register(String user, String pass) {
    	String reg = DrinkDB.httpConn(URL_START + HTTP_USERADD_SUFFIX + "&user=" + user + "&pass=" + pass);
    	if (reg == null) {
    		return false;
    	} else {
    		return true;
    	}
    }
    
    /* Returns true if this input String contains all legal characters. Otherwise returns false.
	 * Legal characters for input include all alphabetic characters.
	 */
	private boolean validChar(String input) {
		// a = 97, z = 122
		for (int i = 0; i < input.length(); i++) {
			if (input.charAt(i) < 'a' || input.charAt(i) > 'z') {
				return false;
			}
		}
		return true;
	}
}
